/**
 * Created by Ting on 2016/2/19.
 */
var console = window.console || { log : function(){} };

window.H = {version:'20160219'};

(function(){
    var global = {};

    function require(scripts , callback){
        var len = scripts.length, i=0;
        var process = function(){
            if(i<len) {
                console.log('load:',scripts[i]);
                if(!global[scripts[i]]){
                    loadScript(scripts[i] , function(){
                        global[scripts[i]] = true;
                        i++;
                        process();
                    });
                }else{
                    i++;
                    process();
                }
            }
            else if(i>=len){
                if( typeof(callback) == 'function'){
                    callback();
                }
            }
        }

        process();
    }

    H.require = require;

    H.module = function(mod) {
        var nc = mod.split("."), o = window , i, l = nc.length;
        for (i = 0 ; i < l; i++) {
            o = o[nc[i]] = o[nc[i]] || {};
        }
        return o;
    };

    H.extend = function(dist , src){
        for(var i in src){
            dist[i] = src[i];
        }
        return dist;
    };
    
    //http://static.logomap.com/upload/

    H.debounce = function(func, wait, immediate) {
        var timeout, result;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) result = func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) result = func.apply(context, args);
            return result;
        };
    };

    H.parse = function(str, data) {
        return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) {
            var value = data[key];
            if (value === undefined) {
                console.log('No value provided for variable ' + str);
                value = "{" + key + "}";
            } else if (typeof value === 'function') {
                value = value(data);
            }
            return value;
        })
    };

    H.unescape = (function(){
        var m = '(?:' +
                ['&amp;','&lt;','&gt;','&quot;','&#x27;','&#x60;'].join('|') +
                ')',
            obj = {'&amp;':'&','&lt;':'<','&gt;':'>','&quot;':'"','&#x27;':"'",'&#x60;':'`'};

        return function(str){
            return str.replace(RegExp(m,'g') , function(match){
                return obj[match];
            });
        }
    }());

    H.para = (function(){
        var url = location.search,
            reg = /(?:\?|&)?([^=]+)=([^&]*)/ig,
            obj = {},
            m;// = url.match(reg);

        while(m = reg.exec(url)) obj[m[1]] = m[2];

        return function(v){
            if(arguments.length == 0) return obj;
            else return obj[v];
        }
    })();

    H.hash = (function(){
        var url = location.hash,
            reg = /(?:#|&)?([^=]+)=([^&]*)/ig,
            obj = {},
            m;// = url.match(reg);

        while(m = reg.exec(url)) obj[m[1]] = m[2];

        return function(v){
            if(arguments.length == 0) return obj;
            else return obj[v];
        }
    })();

    

    H.dom = {
        create : function(tag , cls , style , parent)
        {
            var el = document.createElement(tag);
            if (cls) el.className = cls;
            if (style) el.setAttribute("style", style);
            if (parent) parent.appendChild(el);
            return el;
        }
    }

    H.logger = function(v){
        console.log(v);
    }

}());

/**
 * 轻量模板
 */
(function(){
    var helper = {
        path:function(v){
            return H.config.path + v;
        },
        //date : H.dateFormat,
        number : function(str){
            return parseInt(str);
        },
        left : function(str , l){
            return (str.length < l) ? str : (str.substring(0,l)+'...')
        },
        img : function(v,fix){
            return v ? (fix || '/upload/') + v : '';
        },
        // 转义
        html : function(v){
            return H.unescape(v);
        },
        left : function(str , v){
            if(!str) return '';
            if(v===undefined) v = 100;
            return str.length > v ? str.substring(0,v) + ' ... ' : str;
        }
    }

    var template = ((function(){
        var cache = {};

        function tmpl(str, data , h){

            var rep = '__&&__', key_stamp = 0;
            var source = str
                .replace(/[\r\n]/g, "")
                /*                .replace(/<each\s+([\s\S]*?)>/g,function(a , b){
                 return '<% for(var key in '+b+'){ var data = '+b+'[key]; %>';
                 })
                 .replace(/<\/each>/g,'<% } %>')*/
                .replace(/<each\s+([\s\S]*?\s*)>([\s\S]*?)<\/each>/g,function(a , obj , cnt){
                    var k = '__key__'+(++key_stamp);
                    var d = '__data__'+key_stamp;
                    return [
                        '<% for(var '+k+' in '+obj+'){ var '+d+' = '+obj+'['+k+']; %>',
                        cnt.replace(/\{\{@\}\}/g,'{{'+d+'}}').replace(/\{\{([^\}]+?)\}\}/g,'{{'+d+'.$1}}').replace(/<iif\s+([\s\S]*?\s*)>/g,function($0,$1){
                            return '<% if('+d+'.'+$1+'){ %>';
                        }),
                        '<% } %>'
                    ].join('');
                })
                .replace(/<iif\s+([\s\S]*?\s*)>/g,function(a,b){
                    return '<% if('+b+'){ %>';
                })
                .replace(/<\/iif>/g,function(){
                    return '<% } %>';
                })
                .replace(/\{\{([^\}]+?)\}\}/g, "<%=$1%>")
                .replace(/<%([\s\S]*?)%>/g,function(a){
                    return a.replace(/'/g,rep).replace(/\|\|/g,'__or__');
                })
                .replace(/<%\s?=\s?([\s\S]*?)%>/g,function(a,b){
                    //管道风格过滤器
                    var filter = b.split('|'), func = filter[0],i = 0,l = filter.length;
                    while(++i<l){
                        if(filter[i].indexOf('(')==-1){
                            func = 'helper.' + filter[i] + '(' + func + ')';
                        }else{
                            func = 'helper.' + filter[i].replace('(','('+func+',');
                        }
                    }
                    return rep+","+ func + ","+rep;
                })
                .replace(/<%\s?([\s\S]*?)%>/g,rep+");$1;p.push("+rep);
            source = source.replace(/'/g,"\\'")
                .replace(/__or__/g,'||')
                .replace(new RegExp(rep,'g'),"'");

            source =
                "var p=[],print=function(){p.push.apply(p,arguments);};" +
                "p.push('" + source + "');return p.join('');";
            //console.log(source)
            try {
                var fn =  new Function("args",'helper',source);
            } catch (e) {
                e.source = source;
                throw e;
            }
            // 修改this,默认为this = data
            var _tpl = function(data,args,filter) {
                //扩展过滤器
                args || (args = {});
                if(!filter) filter = {};
                filter = H.extend(filter, helper);
                return fn.call(data, args , filter);
            };
            _tpl.source = 'function(args){\n' + source + '}';
            return data ? _tpl( data ,{} ,h) : _tpl;
        };

        return tmpl;

    })());


    H.vm = {
        template:template,
        helper : function(a){
            H.extend(helper,a);
        }
    }
}());


/**
 * 一些 ui工具
 */
(function(){
    var tips = (function(){
        var el = $('<div style="position:absolute;z-index:9999;width:100%;padding:12px;margin:0;background-color: #DE654E;left:0;top:0;color:#fff;"></div>');
        var handler;
        return function(str ,  parent){
            el.appendTo(parent || $('body')).html(str).fadeIn(250);
            if(handler) clearTimeout(handler);
            handler = setTimeout(function(){
                el.fadeOut(250)
            },1500);
        }
    }());

    H.ui = {
        tips : tips
    }
}());